//
//  HOAnalyzeViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/17/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOAnalyzeViewController.h"
#import "HOUtils.h"
#import "HOStatisticsViewController.h"
#import "HOConstants.h"
#import "HODefine.h"
#import "HOUIMgr.h"

#define ZOOM_STEP 1.5f
@interface HOAnalyzeViewController ()<UIWebViewDelegate, UIScrollViewDelegate>
{
	UIScrollView *scrollView;
	UIWebView *webView;
	UIButton *selectBtn;
	UIImageView *imgView;
	
}
@property(nonatomic, retain)NSArray *analyzeTypes;
@property(nonatomic, retain)UIView 	*menuPanelView;
@property(nonatomic, retain)NSArray *statisticsTypes;
@end

@implementation HOAnalyzeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	[self initDataSource];
	[self initSubviews];
	[self initPickerView];
	self.menuPanelView = [self createMenuItem];
	[self registerTapGesture];
	[self.view addGestureRecognizer:tapRecognizer];
	[self.view setBackgroundColor:UIColorFromRGB(0xfbfbfb)];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rotated:) name:UIDeviceOrientationDidChangeNotification object:nil];
	
}

- (void)relayout
{
	CGFloat tabBarHeight = self.tabBarController.tabBar.hidden ? 0 : self.tabBarController.tabBar.frame.size.height;
	scrollView.frame = CGRectMake(0,
								  44,
								  self.view.frame.size.width,
								  self.view.frame.size.height - 44 - tabBarHeight);
	webView.frame = CGRectMake(0,
							   0,
							   scrollView.frame.size.width + 200,
							   scrollView.frame.size.height + 200);
	scrollView.contentSize = CGSizeMake(webView.frame.size.width, webView.frame.size.height);
}


//- (void)scrollViewDoubleTapped:(UITapGestureRecognizer *)recognizer{
//	
//	CGPoint pointView = [recognizer locationInView:recognizer.view];
//	CGFloat newZoomScale = scrollView.zoomScale * ZOOM_STEP;
//	
//	CGSize scrollViewSize = scrollView.frame.size;
//	
//	CGFloat width = scrollViewSize.width /newZoomScale;
//	CGFloat heigh = scrollViewSize.height /newZoomScale;
//	CGFloat x = pointView.x - (width/2.0f);
//	CGFloat y = pointView.y - (heigh/2.0f);
//	
//	CGRect rectToZoomTo = CGRectMake(x,y, width, heigh);
//	
//	[scrollView zoomToRect:rectToZoomTo animated:YES];
//	
//	
//}
//
//- (void)scrollTwoFingerTapped:(UITapGestureRecognizer *)recognizer{
//	
//	CGFloat newZoomScale = scrollView.zoomScale/ZOOM_STEP;
//	
//	newZoomScale = MAX(newZoomScale, scrollView.minimumZoomScale);
//	
//	[scrollView setZoomScale:newZoomScale animated:YES];
//}
//
//
//- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
//{
//	return webView;
//}



// method signature
- (void)rotated:(NSNotification *)notification {
	// do stuff here
	
	CGRect screenBound = [[UIScreen mainScreen] bounds];
	CGSize screenSize = screenBound.size;
	
	scrollView.frame = CGRectMake(0, 44, screenSize.width, screenSize.height- 64 - 44);
	webView.frame = CGRectMake(-50,
							   0,
							   scrollView.frame.size.width + 100,
							   scrollView.frame.size.height);
	
	
	pickerPanelView.frame = CGRectMake(0,
										screenSize.height,
									   screenSize.width,
												260);
	pickerViewImp.frame = CGRectMake(0,
									 44,
									 screenSize.width,
									 216);
	selectBtn.frame = CGRectMake(-1, -1, screenSize.width + 2, 45);
	
	imgView.frame = CGRectMake(0,
							   44,
							   screenSize.width,
							   screenSize.height - 64 - 44);
}

- (void)selectType:(id)sender
{
	[self showPickerView:YES];
}

- (void)requestDataWithType:(int)type
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_DataStatistics}];
}

- (void)initSubviews
{
	
	selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	selectBtn.frame = CGRectMake(-1, -1, self.view.frame.size.width + 2, 45);
	NSString *content = [self.analyzeTypes firstObject];
	selectBtn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	selectBtn.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
	[selectBtn setTitle:content forState:UIControlStateNormal];
	[selectBtn setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
	selectBtn.titleLabel.font = [UIFont systemFontOfSize:15];
	[selectBtn setBackgroundImage:[HOUtils createImageWithColor:[UIColor whiteColor] forView:selectBtn] forState:UIControlStateNormal];
	[selectBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcdcdcd) forView:selectBtn] forState:UIControlStateSelected];
	[selectBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcdcdcd) forView:selectBtn] forState:UIControlStateHighlighted];
	[selectBtn addTarget:self action:@selector(selectType:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:selectBtn];
	[selectBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
	selectBtn.contentEdgeInsets = UIEdgeInsetsMake(0, HO_HORIZONAL_PADDING, 0, 0);
	
	
	imgView = [[UIImageView alloc]
							initWithFrame:CGRectMake(self.view.frame.size.width - 16 - HO_HORIZONAL_PADDING,
													 (44 - 9) / 2,
													 16,
													 9)];
	imgView.image = [UIImage imageNamed:@"ic_baoxiuliebiao_zhankai"];
	[self.view addSubview:imgView];
	self.view.layer.borderColor = [UIColor redColor].CGColor;
	scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,
																0,
																self.view.frame.size.width,
																self.view.frame.size.height - pickerPanelView.frame.size.height - self.tabBarController.tabBar.frame.size.height)];
	
//	scrollView.delegate = self;
//	
//	UIImage *image = [UIImage imageNamed:@"222.jpg"];
//	
//	scrollView.contentSize = image.size;
//	
//	scrollView.maximumZoomScale = 2.0f;
//	scrollView.minimumZoomScale = 1.0f;
//	scrollView.zoomScale = 1.0f;
//	
//	//注册手势（一手指轻按2次）
//	UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(scrollViewDoubleTapped:)];
//	
//	doubleTapRecognizer.numberOfTapsRequired = 2;
//	doubleTapRecognizer.numberOfTouchesRequired = 1;
//	
//	[scrollView addGestureRecognizer:doubleTapRecognizer];
//	
//	//注册手势 （二个手指轻按一次）
//	UITapGestureRecognizer *twoFingerTapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollTwoFingerTapped:)];
//	
//	twoFingerTapRecognizer.numberOfTapsRequired = 1;
//	
//	twoFingerTapRecognizer.numberOfTouchesRequired = 2;
//	
//	[scrollView addGestureRecognizer:twoFingerTapRecognizer];
	
	
	
	
	webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,
														 0,
														 scrollView.frame.size.width,
														 scrollView.frame.size.height)];
	
//	webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	webView.scalesPageToFit = YES;
	webView.multipleTouchEnabled = YES;
	webView.userInteractionEnabled = YES;
//	webView.layer.borderWidth = 1;
	
	webView.delegate = self;
	
	[scrollView addSubview:webView];
	[self.view addSubview:scrollView];
	[self relayout];
}

- (void)displayAnalysis:(UIButton *)btn
{
	NSInteger tag = btn.tag;
	HOStatisticsViewController *viewCtrl = [[HOStatisticsViewController alloc] init];
	viewCtrl.type = (HO_STATISTICS_TYPE)tag;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (UIView *)createMenuItem
{
	UIView *view = [[[UIView alloc]
					 initWithFrame:CGRectMake(self.view.frame.size.width - 151,
											  0,
											  150,
											  8 * 35)] autorelease];
	for(NSInteger i = 0; i < 8; i++)
	{
		HO_STATISTICS_TYPE type = (HO_STATISTICS_TYPE)(i + 1);
		NSString *title = [HOUtils getStatisticsTitle:type];
		[view addSubview:[self createMenuItemWithTitle:title
										  withSelector:@selector(displayAnalysis:)
												 withY:i * 35
											   withTag:type]];
	}
	[view setBackgroundColor:[UIColor whiteColor]];
	view.layer.shadowOffset = CGSizeMake(0.0, 0.0); //shadow on the right and bottom sides.
	view.layer.shadowRadius = 4.0;
	view.layer.shadowOpacity = 0.25;
	[self.view addSubview:view];
	view.hidden = YES;
	return view;
}
- (UIButton *)createMenuItemWithTitle:(NSString *)title withSelector:(SEL)selector withY:(CGFloat)y withTag:(NSInteger)tag
{
	UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
	btn.frame = CGRectMake(- 1,
						   y,
						   152,
						   35);
	
	[btn setTitle:title forState:UIControlStateNormal];
	btn.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
	btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	[btn setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
	btn.titleLabel.font = [UIFont systemFontOfSize:14];
	[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
	btn.tag = tag;
	return btn;
}


- (void)initDataSource
{

//	self.statisticsTypes = @[NSLocalizedString(@"维修部门工作量统计", @"维修部门工作量统计"),
//				  NSLocalizedString(@"个人工作量统计", @"个人工作量统计"),
//				  NSLocalizedString(@"故障区域统计", @"故障区域统计"),
//				  NSLocalizedString(@"故障类型统计", @"故障类型统计"),
//				  NSLocalizedString(@"返修率统计", @"返修率统计"),
//				  NSLocalizedString(@"满意度统计", @"满意度统计"),
//				  NSLocalizedString(@"维修效率统计", @"维修效率统计"),
//				  NSLocalizedString(@"个人得分统计", @"个人得分统计")];
	self.analyzeTypes = @[NSLocalizedString(@"报修有偿无偿分析", @"报修有偿无偿分析"),
					   NSLocalizedString(@"报修故障分类统计", @"报修故障分类统计"),
					   NSLocalizedString(@"报修评价分类", @"报修评价分类"),
					   NSLocalizedString(@"报修区域统计", @"报修区域统计")];

}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [self.analyzeTypes count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *content = [self.analyzeTypes objectAtIndex:row];
	return content;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	pickerViewSelectRow = row;
}

- (void)didPickDone:(id)sender
{
	[super didPickDone:sender];
	[self loadURL];
}

- (void)viewWillAppear:(BOOL)animated
{
	self.tabBarController.tabBar.hidden = self.displayBackBtn;
	self.navigationItem.hidesBackButton = !self.displayBackBtn;
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"数据分析", @"数据分析")];
	[self displayRightButtonItemWithTitle:NSLocalizedString(@"数据统计", @"数据统计")];
	[self loadURL];
	CGRect screenBound = [[UIScreen mainScreen] bounds];
	CGSize screenSize = screenBound.size;
	webView.frame = CGRectMake(0,
							   44,
							   screenSize.width,
							   screenSize.height- 64 - (self.displayBackBtn ? 0 : 44));
	[self relayout];
	

}

- (void)hideKeyboard
{
	self.menuPanelView.hidden = YES;
}

- (void)rightButtonItemDidClick
{
//	self.menuPanelView.hidden = !self.menuPanelView.hidden;
	
	HOStatisticsViewController *viewCtrl = [[HOStatisticsViewController alloc] init];
	viewCtrl.type = STATISTICS_TYPE_DEPT_WORKLOAD;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}
- (void)loadURL
{
	NSString *content = [self.analyzeTypes objectAtIndex:pickerViewSelectRow];
	[selectBtn setTitle:content forState:UIControlStateNormal];
	NSString *token = [[HOUIMgr sharedInstance] getToken];
	NSString *url = [NSString stringWithFormat:@"%@/Api/Statistics/Analysis/chartype/%d?Token=%@", kServerPath, (int)pickerViewSelectRow, token];
	NSURL *URL =[NSURL URLWithString:url];
	[webView loadRequest:[NSURLRequest requestWithURL:URL]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
	[self showLoadingView:YES];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	[self showLoadingView:NO];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	[self popupHintView:@"统计信息异常"];
}

- (void)dealloc
{
	self.menuPanelView = nil;
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
	[self.view removeGestureRecognizer:tapRecognizer];
	[webView release];
	webView = nil;
	[imgView release];
	[super dealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
